package sk.bielyvlk.vlkgps;

import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

import sk.bielyvlk.vlkgps.db.DbHelper;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.AdapterView.OnItemLongClickListener;

public class WayPointsList extends ListActivity implements ServiceConnection, OnItemLongClickListener {
	public static final String TAG = "vlkGPS.WayPointsList";

	VlkGpsService vlkGpsService = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.d(TAG, "onStart");
		try {
			Intent serviceIntent = new Intent(WayPointsList.this, VlkGpsService.class);
			bindService(serviceIntent, this, 0);
		} catch (Exception e) {
			Log.e(TAG, e.toString());
		}
		getListView().setOnItemLongClickListener(this);
	}

	@Override
	public void onStart() {
		super.onStart();
		Log.d(TAG, "onStart");
	}

	@Override
	public void onRestart() {
		super.onRestart();
		Log.d(TAG, "onRestart");
	}

	@Override
	public void onResume() {
		super.onResume();
		Log.d(TAG, "onResume");
	}

	@Override
	public void onPause() {
		super.onPause();
		Log.d(TAG, "onPause");
	}

	@Override
	public void onStop() {
		super.onStop();
		Log.d(TAG, "onStop");
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		Log.d(TAG, "onDestroy");
	}

	@Override
	public void onServiceConnected(ComponentName name, IBinder service) {
		try {
			Log.d(TAG, "onServiceConnected");
			vlkGpsService = ((VlkGpsService.LocalBinder) service).getService();
			DbHelper dbHelper = vlkGpsService.getDbHelper();
			Cursor c = dbHelper.getWaypointList();
			String[] from = new String[] { "name", "name"};
			int[] to = new int[] { R.id.text1, R.id.text2, };
			SimpleCursorAdapter waypoints = new SimpleCursorAdapter(this, R.layout.waypoint_row, c, from, to);
			setListAdapter(waypoints);
		} catch (Exception e) {
			Log.d(TAG, e.toString());
		}
	}

	@Override
	public void onServiceDisconnected(ComponentName name) {
		Log.d(TAG, "onServiceDisconnected");
		vlkGpsService = null;
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		Log.d(TAG, "item clicked: " + id);
	}

	private void exportWayPoint(long id) {
		DbHelper dbHelper = vlkGpsService.getDbHelper();
		SQLiteDatabase db = dbHelper.getReadableDatabase();
		Cursor c = db.rawQuery("SELECT name, description, symbol, time, lon, lat, alt, acc, maxzoom FROM waypoints WHERE _id = " + id + ";", null);
		if (c.getCount() == 0)
			return;
		c.moveToFirst();
		if (c.isNull(0))
			return;
		try {
			double lon = c.getLong(4) / DbHelper.DB_DEGREES_MULT;
			double lat = c.getLong(5) / DbHelper.DB_DEGREES_MULT;
			double alt = c.getLong(6) / DbHelper.DB_METERS_MULT;
			double acc = c.getLong(7) / DbHelper.DB_METERS_MULT;
			SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
			formater.setTimeZone(TimeZone.getTimeZone("GMT"));
			String time = formater.format(new Date(c.getLong(3)));
			FileWriter file = new FileWriter("/sdcard/vlkgps/" + c.getString(0) + ".gpx");
			file.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n");
			file.write("<gpx version=\"1.1\" creator=\"vlkGPS - http://vlkgps.bielyvlk.sk\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://www.topografix.com/GPX/1/1\" xsi:schemaLocation=\"http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd\">\r\n");
			file.write("  <wpt lon=\"" + lon + "\" lat=\"" + lat + "\">\r\n");
			file.write("    <name>" + c.getString(0) + "</name>\r\n");
			file.write("    <desc>" + c.getString(1) + "</desc>\r\n");
			file.write("    <sym>" + c.getString(2) + "</sym>\r\n");
			file.write("    <time>" + time + "</time>\r\n");
			file.write("    <ele>" + alt + "</ele>\r\n");
			file.write("    <extensions>\r\n");
			file.write("      <maxzoom>" + acc + "</maxzoom>\r\n");
			file.write("    </extensions>\r\n");
			file.write("  </wpt>\r\n");
			file.write("</gpx>\r\n");
			file.close();
		} catch (IOException e) {
			Log.e(TAG, e.toString());
		}
		c.close();
	}

	private long selectedWayPointId = 0;
	//private View selectedView = null;

	@Override
	public boolean onItemLongClick(AdapterView<?> l, View v, int position, long id) {
		DbHelper dbHelper = vlkGpsService.getDbHelper();
		selectedWayPointId = id;
		//selectedView = v;
		try {
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setTitle(dbHelper.getWaypointName(selectedWayPointId));
			builder.setItems(R.array.WayPointSubmenu, new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface d, int id) {
					Log.d(TAG, "submenu clicked: " + id + " trackId: " + selectedWayPointId);
					/* TODO don't use numbers */
					switch (id) {
						case 3: /* export */
							exportWayPoint(selectedWayPointId);
							break;
						case 4: /* delete */
							try {
								DbHelper dbHelper = vlkGpsService.getDbHelper();
								dbHelper.deleteWaypoint(selectedWayPointId);
								finish();
							} catch (Exception e) {
								Log.e(TAG, e.toString());
							}
							break;
					}
				}
			});
			builder.create().show();
		} catch (Exception e) {
			Log.e(TAG, e.toString());
		}
		return true;
	}

}
